package com.fudan.es.aggs.request.handler.metric;

import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.stereotype.Component;

import com.fudan.es.Aggs;
import com.fudan.es.aggs.ConstString;
import com.fudan.es.entity.FieldMeta;
import com.fudan.es.entity.MetricPack;

public class SplitHandler extends MetricHandler{

	@Override
	public AggregationBuilder build(MetricPack metric) {
		FieldMeta field = metric.getField();
		FieldMeta grainField = metric.getGrain();
		TermsAggregationBuilder aggs = Aggs.terms(field).size(metric.getSize());
		if(metric.getMissing()!=null) {
			aggs.missing(metric.getMissing());
		}
		if(grainField == null) {
			return aggs;
		}else if(ConstString.ROOT_PATH.equals(grainField.getName())){
			return aggs.subAggregation(Aggs.reverse(ConstString.GRAIN_TAG+"$"+grainField.getName()));
		}else {
			return aggs.subAggregation(Aggs.reverse(ConstString.GRAIN_TAG+"$"+grainField.getId(), grainField.getName()));
		}
	}

}
